<script setup lang="ts">
import { loginByQQ, sendMobileCode, bindMobile } from '@/services/user'
import { onMounted, ref, onUnmounted } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import { Toast, type FormInstance } from 'vant'
import type { User } from '@/types/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { useSendMobileCode } from '@/composable'

const store = useUserStore()
const router = useRouter()

// 1. 属性
const openId = ref('') // QQ扫码登录成功后可以拿到的唯一标识
const isBind = ref(true) // 当前登录的QQ是否绑定了手机号, 默认是: 已经绑定

onMounted(() => {
  // 1.1 判断QQ是否登录成功
  if (window.QC.Login.check()) {
    // 1.2 获取用户唯一身份标识
    window.QC.Login.getMe((id: string) => {
      openId.value = id
      // 1.3 项目中的qq登录
      loginByQQ(id)
        .then((res) => {
          // 登录成功 (当前QQ已经绑定了手机号, 返回用户信息)
          console.log('登录成功', res.data) // 用户信息
          loginSuccess(res.data)
        })
        .catch(() => {
          // 登录失败 (当前QQ没有绑定手机号, 需要绑定手机号)
          console.log('登录失败')
          isBind.value = false
        })
    })
  }
})

// 2. 手机绑定
const mobile = ref('')
const code = ref('')
const bind = async () => {
  // 2.1 调用绑定手机号的接口函数
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  // 2.2 登录成功
  console.log(res.data) // 用户信息
  loginSuccess(res.data)
}

// 处理登录成功后的业务
const loginSuccess = (user: User) => {
  // 1. 存储用户信息到仓库
  store.setUser(user)
  // 2. 提示用户登录成功
  Toast.success('登录成功~')
  // 3. 跳转到个人中心
  // 要获取returnUrl的值
  router.replace(store.returnUrl || '/user')
  // 清空回跳地址
  store.setReturnUrl('')
}

// 3. 获取验证码倒计时
const { form, time, send } = useSendMobileCode(mobile, 'bindMobile')
</script>

<template>
  <div class="login-page" v-if="!isBind">
    <cp-nav-bar title="绑定手机号"></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form" @submit="bind">
      <van-field
        v-model="mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="mobileRules"
      ></van-field>
      <van-field
        v-model="code"
        name="code"
        placeholder="请输入验证码"
        :rules="codeRules"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">{{
            time > 0 ? `${time}s后再次发送` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
